package research.ui.views;

import java.util.Calendar;
import java.util.List;

import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;

import research.model.ResearchHierarchy;
import research.ui.views.comparators.ResearchDateComparator;
import research.ui.views.filters.ResearchDateFilter;

public class ResearchView extends HierarchyView {
	public static final String ID = "research.ui.views.ResearchView";
	
	private DateTime start;
	private DateTime finish;

	public ResearchView() {
		super(new ResearchHierarchy());
	}

	@Override
	protected void renderAdditionalFilters(Composite parent) {
		super.renderAdditionalFilters(parent);
		
		FormToolkit toolkit = new FormToolkit(parent.getDisplay());

		Section section = toolkit.createSection(parent, Section.EXPANDED
				| Section.TITLE_BAR | Section.TWISTIE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		section.setLayoutData(gd);
		section.setText("По времени");
		Composite composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(2, false));
		section.setClient(composite);
		gd = new GridData();
		Label label = toolkit.createLabel(composite, "От:");
		label.setLayoutData(gd);
		gd = new GridData();
		start = new DateTime(composite, SWT.DATE);
		start.setLayoutData(gd);

		gd = new GridData();
		label = toolkit.createLabel(composite, "До:");
		label.setLayoutData(gd);
		gd = new GridData();
		finish = new DateTime(composite, SWT.DATE);
		finish.setLayoutData(gd);
	
	}
	
	@Override
	protected void renderAdditionalSorters(Composite parent) {
		super.renderAdditionalSorters(parent);
		
		GridData gd = new GridData();
		Button sortName = new Button(parent, SWT.NONE);
		sortName.setText("По дате");
		sortName.setLayoutData(gd);
		sortName.addSelectionListener(new SortBtnSelectionListener(new ResearchDateComparator()));
	
	}
	
	@Override
	protected ViewerComparator getComparator() {
		return new ResearchDateComparator();
	}

	@Override
	protected void addAdditionalFilters(List<ViewerFilter> filters) {
		super.addAdditionalFilters(filters);
		Calendar sdate = Calendar.getInstance();
		sdate.set(start.getYear(), start.getMonth(), start.getDay(), start
				.getHours(), start.getMinutes(), start.getSeconds());

		Calendar fdate = Calendar.getInstance();
		fdate.set(finish.getYear(), finish.getMonth(), finish.getDay(), finish
				.getHours(), finish.getMinutes(), finish.getSeconds());
		
		filters.add(new ResearchDateFilter(sdate.getTime(), fdate.getTime()));
	}

	/*private TreeViewer viewer;
	private DrillDownAdapter drillDownAdapter;
	private Action actionEdit;
	private Action actionAdd;
	private Action actionScr;
	private Action actionPhoto;
	private Action actionDelete;
	private Action actionRefresh;
	

	class NameSorter extends ViewerSorter {
	}

	public ResearchView() {
	}

	public void createPartControl(Composite parent) {
		GridLayout la = new GridLayout(1, false);
		parent.setLayout(la);
		la.horizontalSpacing = 0;
		la.verticalSpacing = 0;
		la.marginHeight = 0;
		la.marginWidth = 0;

		GridData gd = new GridData(GridData.FILL_BOTH);
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		drillDownAdapter = new DrillDownAdapter(viewer);
		viewer.setContentProvider(new EntityContentProvider(new ResearchHierarchy()));
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());
		viewer.getControl().setLayoutData(gd);

		loadData();
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
		updateActionEnablement();

	}

	private void loadData() {
		viewer.setInput(PersistenceManager.getInstance());
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				ResearchView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(actionEdit);
		manager.add(actionAdd);
		manager.add(actionDelete);
		manager.add(new Separator());
		manager.add(actionRefresh);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(actionEdit);
		manager.add(actionAdd);
		manager.add(actionScr);
		manager.add(actionPhoto);
		manager.add(actionDelete);
		manager.add(new Separator());
		manager.add(actionRefresh);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}

	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(actionEdit);
		manager.add(actionAdd);
		manager.add(actionDelete);
		manager.add(actionRefresh);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {
		actionEdit = new Action() {
			public void run() {
				editSelected(viewer.getSelection());
			}
		};
		actionEdit.setText("Edit");
		actionEdit.setToolTipText("Edit");
		actionEdit.setImageDescriptor(Activator
				.getImageDescriptor("icons/edit.png"));

		actionAdd = new Action() {
			public void run() {
				addToSelected(viewer.getSelection());
			}
		};
		actionAdd.setText("Add");
		actionAdd.setToolTipText("Add");
		actionAdd.setImageDescriptor(Activator
				.getImageDescriptor("icons/add.png"));
		
		actionScr = new Action() {
			public void run() {
				addScrToSelected(viewer.getSelection());
			}
		};
		actionScr.setText("Add scratch experiment");
		actionScr.setToolTipText("Add scratch experiment");
		actionScr.setImageDescriptor(Activator
				.getImageDescriptor("icons/add.png"));
		
		actionPhoto = new Action() {
			public void run() {
				addPhotoToSelected(viewer.getSelection());
			}
		};
		actionPhoto.setText("Add photo experiment");
		actionPhoto.setToolTipText("Add photo experiment");
		actionPhoto.setImageDescriptor(Activator
				.getImageDescriptor("icons/add.png"));

		actionDelete = new Action() {
			public void run() {
				deleteSelected(viewer.getSelection());
			}
		};
		actionDelete.setText("Delete");
		actionDelete.setToolTipText("Delete");
		actionDelete.setImageDescriptor(Activator
				.getImageDescriptor("icons/delete.png"));

		actionRefresh = new Action() {
			public void run() {
				viewer.refresh();
			}
		};
		actionRefresh.setText("Refresh");
		actionRefresh.setToolTipText("Refresh");
		actionRefresh.setImageDescriptor(Activator
				.getImageDescriptor("icons/refresh.png"));

		viewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				updateActionEnablement();
			}
		});
	}

	private void updateActionEnablement() {
		IStructuredSelection sel = (IStructuredSelection) viewer.getSelection();
		Object single = sel.size() == 1 ? sel.getFirstElement() : null;
		actionEdit.setEnabled(single instanceof Research
				|| single instanceof Exp_viscosity || single instanceof Exp_strength || single instanceof Exp_scratch
				|| single instanceof Exp_photo || single instanceof Stabilizer || single instanceof Sample);
		actionAdd.setEnabled(true
//				single instanceof Research
//				|| single instanceof CalanderConnector
//				|| single instanceof FormulaConnector
//				|| single instanceof Exp_viscosity || single instanceof Exp_strength || single instanceof Exp_scratch
//				|| single instanceof Exp_photo || single instanceof Stabilizer || single instanceof Sample
				);
		actionDelete.setEnabled(single instanceof Research
				|| single instanceof Exp_viscosity || single instanceof Exp_strength || single instanceof Exp_scratch
				|| single instanceof Exp_photo || single instanceof Stabilizer || single instanceof Sample);
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(
					org.eclipse.jface.viewers.DoubleClickEvent event) {
				editSelected(event.getSelection());
			};
		});
	}

	private void editSelected(ISelection sel) {
		Object obj = ((StructuredSelection) sel).getFirstElement();
		try {
			if (obj instanceof Research) {
				EditorFactory.openEditor(getViewSite(), obj);
			} else if (obj instanceof Exp_viscosity) {
				EditorFactory.openEditor(getViewSite(), obj);
			} else if (obj instanceof Exp_strength) {
				EditorFactory.openEditor(getViewSite(), obj);
			} else if (obj instanceof Exp_scratch) {
				EditorFactory.openEditor(getViewSite(), obj);
			} else if (obj instanceof Exp_photo) {
				EditorFactory.openEditor(getViewSite(), obj);
			} else if (obj instanceof Stabilizer) {
				EditorFactory.openEditor(getViewSite(), obj);
			} else if (obj instanceof Sample) {
				EditorFactory.openEditor(getViewSite(), obj);
			}

		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}

	private void addToSelected(ISelection sel) {
		Object obj = ((StructuredSelection) sel).getFirstElement();

		try {
			if (obj instanceof Research) {
				Sample form = Sample.getNew();
				EditorFactory.openEditor(getViewSite(), form, (Research)obj);
			} else if (obj instanceof Exp_scratch) {
				Exp_scratch form = Exp_scratch.getNew();
				EditorFactory.openEditor(getViewSite(), form, ((Exp_scratch) obj)
						.getSample());
			} else if (obj instanceof Exp_photo) {
				Exp_photo form = Exp_photo.getNew();
				EditorFactory.openEditor(getViewSite(), form, ((Exp_photo) obj)
						.getSample());
			} else if (obj instanceof Stabilizer) {
				Stabilizer form = Stabilizer.getNew();
				EditorFactory.openEditor(getViewSite(), form,
						null);
			} else if (obj instanceof Sample) {
				Sample form = Sample.getNew();
				EditorFactory.openEditor(getViewSite(), form,
						((Sample) obj).getResearch());
			} else if (obj == null)
			{
//				Research res = Research.getNew();
//				EditorFactory.openEditor(getViewSite(), res,
//						container);
			}
		} catch (PartInitException e) {
			e.printStackTrace();
		}

	}
	
	private void addScrToSelected(ISelection sel) {
		Object obj = ((StructuredSelection) sel).getFirstElement();

		try {
			if (obj instanceof Sample) {
				Exp_scratch form = Exp_scratch.getNew();
				EditorFactory.openEditor(getViewSite(), form, (Sample)obj);
			} 
		} catch (PartInitException e) {
			e.printStackTrace();
		}

	}
	
	private void addPhotoToSelected(ISelection sel) {
		Object obj = ((StructuredSelection) sel).getFirstElement();

		try {
			if (obj instanceof Sample) {
				Exp_photo form = Exp_photo.getNew();
				EditorFactory.openEditor(getViewSite(), form, (Sample)obj);
			} 
		} catch (PartInitException e) {
			e.printStackTrace();
		}

	}

	private void deleteSelected(ISelection sel) {
		viewer.getTree().setRedraw(false);

		Object obj = ((StructuredSelection) sel).getFirstElement();

//		if (obj instanceof Research) {
//			Research res = (Research) obj;
//			if (new ResearchDAOHibernate().delete(res)) {
//				container.removeResearch(res);
//			} else
//				MessageDialog.openError(this.getViewSite().getShell(), "Error",
//						"Can not delete research.");
//		}
//		if (obj instanceof Exp_scratch) {
//			Exp_scratch res = (Exp_scratch) obj;
//			if (new ScratchDAOHibernate().delete(res)) {
//				res.getSample().removeExp_scratch(res);
//			} else
//				MessageDialog.openError(this.getViewSite().getShell(), "Error",
//						"Can not delete scratch.");
//		}
//		if (obj instanceof Exp_photo) {
//			Exp_photo res = (Exp_photo) obj;
//			if (new PhotoDAOHibernate().delete(res)) {
//				res.getSample().removeExp_photo(res);
//			} else
//				MessageDialog.openError(this.getViewSite().getShell(), "Error",
//						"Can not delete photo.");
//		}
//		if (obj instanceof Sample) {
//			Sample res = (Sample) obj;
//			if (new SampleDAOHibernate().delete(res)) {
//				res.getResearch().removeSample(res);
//			} else
//				MessageDialog.openError(this.getViewSite().getShell(), "Error",
//						"Can not delete stabilizer.");
//		}

		viewer.getTree().setRedraw(true);
	}

	public void setFocus() {
		viewer.getControl().setFocus();
	}

	public void refreshAll() {
		viewer.refresh();
	}*/
}